//
//  MHUserInfoViewController.m
//  WeChat
//
//  Created by senba on 2017/9/21.
//  Copyright © 2017年 CoderMikeHe. All rights reserved.
//

#import "MHUserInfoViewController.h"
#import "MHPhotoManager.h"
#import "MHCommonCell.h"
#import "MHUserInfoViewModel.h"
#import "UITextField+MHExtension.h"
@interface MHUserInfoViewController ()
@property(nonatomic,copy) NSString *nameText;
@property(nonatomic,strong) UIImage *seletedImage;
@property(nonatomic, assign) MHUserInfoViewModel *viewModel;
@property(nonatomic, strong) MHCommonCell *textFeildCell;
@end

@implementation MHUserInfoViewController
@dynamic viewModel;

- (void)viewDidLoad {
    [super viewDidLoad];
 
}

-(void)rightButtonClick
{
    self.nameText = self.textFeildCell.nameTextFeild.text;
    
    if (self.seletedImage) {
        NSData *imageData = UIImageJPEGRepresentation(self.seletedImage, 0.5);
        __weak __typeof(self)weakSelf = self;
        [[weakSelf.viewModel.uploadImageCommand execute:@[imageData]] subscribeNext:^(MHUploadPicture *pic) {
            weakSelf.viewModel.headPic = pic.allSrc;
            weakSelf.viewModel.uploadPic = pic.src;
            weakSelf.viewModel.services.client.swithUrlWithUpload = false;
            self.viewModel.nickName  = self.nameText;
            [self.viewModel.uploadProfileInfoCommand execute:nil];
        }];
    }else
    {
        if(self.nameText.length >0) {
            self.viewModel.nickName  = self.nameText;
            [self.viewModel.uploadProfileInfoCommand execute:nil];
        }
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    MHCommonCell *cell =  [super tableView:tableView cellForRowAtIndexPath:indexPath];
    if (indexPath.row == 1)
    {
        self.nameText =   cell.nameTextFeild.text;
        self.textFeildCell = cell;
    }
    [cell.nameTextFeild mh_limitMaxLength:16];
    cell.nameTextFeild.adjustsFontSizeToFitWidth = YES;
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [super tableView:tableView didSelectRowAtIndexPath:indexPath];
    MHCommonCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    if (indexPath.row == 0) {
        [MHPhotoManager fetchPhotosFromAlbum:self maxImagesCount:1 allowCrop:YES selectedAssets:nil completion:^(NSArray<UIImage *> *photos, NSArray *assets, BOOL isSelectOriginalPhoto, NSArray<NSDictionary *> *infos) {
            UIImage *photo = [photos lastObject];
            cell.avatarView.image = photo;
            self.seletedImage = photo;
       
        } cancel:^{
            
        }];
        
    }else if (indexPath.row == 1)
    {
        self.nameText =   cell.nameTextFeild.text;
        self.textFeildCell = cell;
    }
}
@end
